package entity

import (
	"time"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/constants/db"
	"xr-game-server/core/math"
	"xr-game-server/core/migrate"
	"xr-game-server/core/snowflake"
	"xr-game-server/core/syndb"
)

const (
	TbPlayerBag db.TbName = "player_bags"
)

const (
	PlayerBagRoleId db.TbCol = "role_id"
	PlayerBagCfgId  db.TbCol = "cfg_id"
	PlayerBagVal    db.TbCol = "val"
)

type PlayerBag struct {
	migrate.OneModel
	RoleId uint64 `gorm:"default:0;comment:玩家id"`
	CfgId  uint64 `gorm:"default:0;comment:json配置id"`
	Val    uint64 `gorm:"default:0;comment:数值"`
}

func NewPlayerBag(roleId uint64, cfgId uint64) *PlayerBag {
	ret := &PlayerBag{}
	ret.ID = snowflake.GetId()
	ret.SetCfgId(cfgId)
	ret.SetRoleIdId(roleId)
	return ret
}

func (this *PlayerBag) Add(val uint64, cellNum uint64) uint64 {
	success := math.ChkMax(this.Val, val, cellNum)
	this.Val += success
	this.SetVal(this.Val)
	return success
}
func (this *PlayerBag) Consume(val uint64) {
	if val >= this.Val {
		this.Val = common.Zero
	} else {
		this.Val -= val
	}
	this.SetVal(this.Val)
}

func (receiver *PlayerBag) SetRoleIdId(roleId uint64) {
	receiver.RoleId = roleId
	syndb.AddDataToLazyChan(TbPlayerBag, PlayerBagRoleId, &syndb.ColData{
		IdVal:  receiver.ID,
		ColVal: roleId,
	})
}

func (receiver *PlayerBag) SetCfgId(cfgId uint64) {
	receiver.CfgId = cfgId
	syndb.AddDataToLazyChan(TbPlayerBag, PlayerBagCfgId, &syndb.ColData{
		IdVal:  receiver.ID,
		ColVal: cfgId,
	})
}

func (receiver *PlayerBag) SetVal(val uint64) {
	receiver.Val = val
	receiver.SetUpdatedAt(time.Now())
	syndb.AddDataToLazyChan(TbPlayerBag, PlayerBagVal, &syndb.ColData{
		IdVal:  receiver.ID,
		ColVal: val,
	})
}

func (receiver *PlayerBag) SetCreatedAt(val time.Time) {
	receiver.CreatedAt = val
	syndb.AddDataToLazyChan(TbPlayerBag, db.CreatedAtName, &syndb.ColData{
		IdVal:  receiver.ID,
		ColVal: val,
	})
}

func (receiver *PlayerBag) SetUpdatedAt(val time.Time) {
	receiver.UpdatedAt = val
	syndb.AddDataToLazyChan(TbPlayerBag, db.UpdatedAtName, &syndb.ColData{
		IdVal:  receiver.ID,
		ColVal: val,
	})
}

func initPlayerBag() {
	syndb.RegLazyWithSmall(TbPlayerBag, db.CreatedAtName)
	syndb.RegLazyWithSmall(TbPlayerBag, db.UpdatedAtName)

	syndb.RegLazyWithSmall(TbPlayerBag, PlayerBagRoleId)
	syndb.RegLazyWithSmall(TbPlayerBag, PlayerBagCfgId)
	syndb.RegLazyWithMiddle(TbPlayerBag, PlayerBagVal)

	migrate.AutoMigrate(&PlayerBag{})
}
